(function() {

function JsonEscpae(str) {
  return str;
  // TODO : json 特殊字符集合？
  str = str.replace(/\t/g, '\\t');
  str = str.replace(/"/g,  '\\"');
  str = str.replace(/\\/g, '\\\\');
  return str;
}

function NaiveStringify(o) {
  if(!o)  return null;
  var is_array = o instanceof Array;
  var res = '{';
  if (is_array) {
    res = '['; 
  }
  var m_idx = 0;
  for(var m in o)
  {
    if (m_idx++ > 0) {
      res += ','
    }
    if (!is_array) {
      res += m + ':';
    }
    if (typeof o[m] == 'object') {
      res += JsonEscpae(NaiveStringify(o[m]));
    } else if(typeof o[m] == 'string') {
      res += '"' + o[m] + '"';
    } else {
      res += o[m];
    }
  }
  
  res += (is_array ? ']' : '}');
  return res;
}

function NaiveParse(str) {
  $.globalEval('var o = ' + str + ';');
  return o;
}

window.Parse = null;
window.Stringify = null;


if (window.JSON && JSON.parse && JSON.stringify) {
  Parse = JSON.parse;
  Stringify = JSON.stringify;
} else {
  Parse = NaiveParse;
  Stringify = NaiveStringify;
}

})();

(function() {

if (window.localStorage 
    || !/MSIE/.test(navigator.userAgent)){
  return;
}

var UserData = function(file_name) {
  if (!file_name) {
    file_name="user_data_default";
  }
  var dom = document.createElement('input');
  dom.type = "hidden";
  dom.addBehavior("#default#userData");
  document.body.appendChild(dom);
  dom.save(file_name);
  this.file_name = file_name;
  this.dom = dom;
  return this;
};

UserData.prototype = {
  setItem:function(k, v) {
    this.dom.setAttribute(k,v);
    this.dom.save(this.file_name);
  },
  getItem:function(k) {
    this.dom.load(this.file_name);
    return this.dom.getAttribute(k);
  },
  removeItem:function(k) {
    this.dom.removeAttribute(k);
    this.dom.save(this.file_name);
  },
  clear:function() {
    this.dom.load(this.file_name);
    var now = new Date();
    now = new Date(now.getTime()-1);
    this.dom.expires = now.toUTCString();
    this.dom.save(this.file_name);
  }
};

$(document).ready(function() {
  window.localStorage = new UserData("qim_storage");
});

})();


window.LocalStore = {
  Write : function(key, value) {
    if (window.localStorage) {
      localStorage.setItem(key, Stringify(value));
    }
  },
  Read : function(key) {
    if (window.localStorage) {
      var s = localStorage.getItem(key);
      return Parse(s);
    }
    return null;
  },
  Remove : function(key) {
    if (window.localStorage) {
      localStorage.removeItem(key);
    }
  }
};


